<?php
// ========================== 文件说明 ==========================//
// 本文件说明：前后台公共函数
// --------------------------------------------------------------//
// 本程序作者：angel
// --------------------------------------------------------------//
// 本程序版本：SaBlog-X Ver 1.6
// --------------------------------------------------------------//
// 本程序主页：http://www.sablog.net
// ========================== 开发环境 ==========================//
// register_globals = Off
// --------------------------------------------------------------//
// magic_quotes_gpc = On
// --------------------------------------------------------------//
// safe_mode = On
// --------------------------------------------------------------//
// Windows server 2003 & Linux & FreeBSD
// --------------------------------------------------------------//
// Apache/1.3.33 & PHP/4.3.2 & MySQL/4.0.17
// --------------------------------------------------------------//
// Apache/1.3.34 & PHP/4.4.1 & MySQL/5.0.16
// --------------------------------------------------------------//
// Apache/2.0.55 & PHP/5.1.1 & MySQL/5.0.15
// --------------------------------------------------------------//
// Copyright (C) Security Angel Team All Rights Reserved.
// ==============================================================//

if(!defined('SABLOG_ROOT')) {
	exit('Access Denied');
}

// 日历获取日历部分
function calendar($y,$m){
	global $DB,$db_prefix,$options,$timestamp,$timeoffset;
	!$y && $y = sadate('Y');
	!$m && $m = sadate('m');

	//当前月等于1
	if ($m == 1) {
		$lastyear = $y-1;
		$lastmonth = 12;
		$nextmonth = $m+1;
		$nextyear = $y;
	} elseif ($m == 12) {
		$lastyear = $y;
		$lastmonth = $m - 1;
		$nextyear = $y + 1;
		$nextmonth = 1;
	} else {
		$lastmonth = $m - 1;
		$nextmonth = $m + 1;
		$lastyear = $nextyear = $y;
	}
	if ($nextmonth < 10) $nextmonth = '0'.$nextmonth;
	if ($lastmonth < 10) $lastmonth = '0'.$lastmonth;

	$weekday   = sadate('w',mktime(0,0,0,$m,1,$y));
	$totalday  = sadate('t',mktime(0,0,0,$m,1,$y));
	list($start, $end) = explode('-', gettimestamp($y,$m));
	// 动态缓存
	$expiration	= 0;
	$cachefile = SABLOG_ROOT.'cache/cache_calendar.php';

	if (($m != sadate('m')) || ($y != sadate('Y')) || (!@include($cachefile)) || $expiration < $timestamp) {
		$query = $DB->query("SELECT dateline FROM {$db_prefix}articles WHERE visible='1' AND dateline >= '".correcttime($start)."' AND dateline < '".correcttime($end)."'");
		$datelines = array();
		$articledb = array();
		while($article = $DB->fetch_array($query)) {
			$datelines[] = sadate('Y-m-j',$article['dateline']);
			$day = sadate('j', $article['dateline']);
			if (!isset($articledb[$day])) {
				$articledb[$day]['num'] = 1;
			} else {
				$articledb[$day]['num']++;
			}
		}
		$br = 0;
		$ret['html'] = "<tr>\n";
		for ($i=1; $i<=$weekday; $i++) {
			$ret['html'] .= "<td class=\"cal_day1\"></td>\n";
			$br++;
		}

		for($i=1; $i<=$totalday; $i++){
			$br++;
			if (in_array($y.'-'.$m.'-'.$i, $datelines)) {
				$td = '<a title="'.$i.'日内发表了'.$articledb[$i]['num'].'篇文章" href="'.$options['url'].'?action=article&amp;setdate='.$y.$m.'&amp;setday='.$i.'&amp;page=1">'.$i.'</a>';
			} else{
				$td = $i;
			}
			if ($i == sadate('d') && $m == sadate('m') && $y == sadate('Y')) {
				$class = 'cal_day2';
			} else {
				$class = 'cal_day1';
			}
			$ret['html'] .= "<td class=\"".$class."\">".$td."</td>\n";
			if ($br >= 7) {
				$ret['html'] .= "</tr>\n<tr>\n";
				$br = 0;
			}
		}
		if ($br != 0) {
			for($i=$br; $i<7;$i++){
				 $ret['html'] .= "<td class=\"cal_day1\"></td>\n";
			}
		}
		$ret['html'] .= "</tr>\n";
		if ($y.$m == sadate('Ym')) {
			$cachedata = "<?php\r\nif(!defined('SABLOG_ROOT')) exit('Access Denied');\r\n\$expiration='".($timestamp + 300)."';\r\n\$ret = unserialize('".addcslashes(serialize($ret), '\\\'')."');\r\n?>";
			if(!writefile($cachefile, $cachedata)) {
				exit('Can not write to calendar cache files, please check directory ./cache/ .');
			}
		}
	}
	$ret['prevmonth'] = $lastyear.$lastmonth;
	$ret['nextmonth'] = $nextyear.$nextmonth;
	$ret['cur_month'] = $m;
	$e_month = ($m < 10) ? str_replace('0', '', $m) : $m;
	$ret['cur_date'] = $y.'年'.$m.'月';
	return $ret;
}

// 高亮标签
function highlight_tag($content, $tag) {
	global $options;
	$tag = trim($tag);

	//有次数的替换
	$content = preg_replace('/>([^<]*)'.$tag.'([^>]*)<([^>]*)([^a])>/i','>$1<a class="taglinks" href="'.gettaglink(urlencode($tag)).'" onclick="tagshow(\''.$tag.'\');return false;">'.htmlspecialchars($tag).'</a>$2<$3$4>', $content, 1); 

	return $content;
}

// 设置title
function settitle($string) {
	global $options;
	$strings = $comma = '';
	if (is_array($string) && count($string)){
		foreach($string as $value) {
			$strings .= $comma.','.htmlspecialchars($value);
			$comma = ',';
		}
		$string = $strings.' - '.$options['title'];
	} else {
		$string = htmlspecialchars($string).' - '.$options['title'];
	}
	return $string;
}

// 分页函数
function multi($num, $perpage, $curpage, $mpurl, $maxpages = 1000) {
	global $options;
	$multipage = '';	
	if (substr($mpurl, 0, 7) != 'http://') {
		$mpurl = $options['url'].$mpurl;
	}
	$realpages = 1;
	if($num > $perpage) {
		$page = 8;
		$offset = 4;
		$realpages = @ceil($num / $perpage);
		$pages = $maxpages && $maxpages < $realpages ? $maxpages : $realpages;
		if($page > $pages) {
			$from = 1;
			$to = $pages;
		} else {
			$from = $curpage - $offset;
			$to = $curpage + $page - $offset - 1;
			if($from < 1) {
				$to = $curpage + 1 - $from;
				$from = 1;
				if(($to - $from) < $page && ($to - $from) < $pages) {
					$to = $page;
				}
			} elseif($to > $pages) {
				$from = $curpage - $pages + $to;
				$to = $pages;
				if(($to - $from) < $page && ($to - $from) < $pages) {
					$from = $pages - $page + 1;
				}
			}
		}

		if ($options['permalink']) {
			$multipage = ($curpage - $offset > 1 && $pages > $page ? '<a href="'.$mpurl.'" class="p_redirect">&laquo; First</a>' : '').($curpage > 1 ? '<a href="'.$mpurl.($curpage - 1).'/" class="p_redirect">&#8249; Prev</a>' : '');
			for($i = $from; $i <= $to; $i++) {
				$multipage .= $i == $curpage ? '<span class="p_curpage">'.$i.'</span>' : '<a href="'.$mpurl.$i.'/" class="p_num">'.$i.'</a>';
			}
			$multipage .= ($curpage < $pages ? '<a href="'.$mpurl.($curpage + 1).'/" class="p_redirect">Next &#8250;</a>' : '').($to < $pages ? '<a href="'.$mpurl.$pages.'/" class="p_redirect">Last &raquo;</a>' : '');
		} else {
			$mpurl .= strpos($mpurl, '?') ? '&amp;' : '?';
			$multipage = ($curpage - $offset > 1 && $pages > $page ? '<a href="'.$mpurl.'page=1" class="p_redirect">&laquo; First</a>' : '').($curpage > 1 ? '<a href="'.$mpurl.'page='.($curpage - 1).'" class="p_redirect">&#8249; Prev</a>' : '');
			for($i = $from; $i <= $to; $i++) {
				$multipage .= $i == $curpage ? '<span class="p_curpage">'.$i.'</span>' : '<a href="'.$mpurl.'page='.$i.'" class="p_num">'.$i.'</a>';
			}
			$multipage .= ($curpage < $pages ? '<a href="'.$mpurl.'page='.($curpage + 1).'" class="p_redirect">Next &#8250;</a>' : '').($to < $pages ? '<a href="'.$mpurl.'page='.$pages.'" class="p_redirect">Last &raquo;</a>' : '');
		}

		$multipage = $multipage ? '<div class="p_bar"><span class="p_info">Total:'.$num.'</span>'.$multipage.'</div>' : '';
	}
	return $multipage;
}

// 清除HTML代码
function html_clean($content) {
	$content = htmlspecialchars($content);
	$content = str_replace("\n", "<br />", $content);
	$content = str_replace("  ", "&nbsp;&nbsp;", $content);
	$content = str_replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;", $content);
	$content = preg_replace("/\[quote=(.*?)\]\s*(.+?)\s*\[\/quote\]/is", "<div style=\"font-weight: bold\">引用 \\1 说过的话:</div><div class=\"quote\">\\2</div>", $content);
	return $content;
}

// 制作description代码
function make_description($content, $limit = 100) {
	if($content) {
		$content = trimmed_title(str_replace(array("\r\n","\n","\r"),'',preg_replace("/\[(attach|face)=([0-9a-z]+)\]/ie", '', html2text($content))), $limit);
		return $content;
	} else {
		return 0;
	}
}

// 高亮显示PHP
function phphighlite($code) {
	if (floor(phpversion())<4) {
		$buffer = $code;
	} else {
		$code = preg_replace("/<style .*?<\/style>/is", "", $code);
		$code = preg_replace("/<script .*?<\/script>/is", "", $code);
		$code = preg_replace("/<br\s*\/?>/i", "\n", $code);
		$code = preg_replace("/<\/?p>/i", "\n", $code);
		$code = preg_replace("/<\/?td>/i", "\n", $code);
		$code = preg_replace("/<\/?div>/i", "\n", $code);
		$code = preg_replace("/<\/?blockquote>/i", "\n", $code);
		$code = preg_replace("/<\/?li>/i", "\n", $code);
		$code = strip_tags($code);
		$code = preg_replace("/\&\#.*?\;/i", "", $code);
		$code = str_replace("&nbsp;&nbsp;&nbsp;", "&nbsp;&nbsp;", $code);
		$code = str_replace("&nbsp;&nbsp;", "&nbsp;", $code);
		$code = str_replace("&nbsp;", "\t", $code);
		$code = str_replace("&quot;", '"', $code);
		$code = str_replace("<br>", "", $code);
		$code = str_replace("<br />", "", $code);
		$code = str_replace("&gt;", ">", $code);
		$code = str_replace("&lt;", "<", $code);
		$code = str_replace("&amp;", "&", $code);
		//$code = str_replace('$', '\$', $code);
		if (!strpos($code,"<?\n") and substr($code,0,4)!="<?\n") {
			$code="<?".trim($code)."?>";
			$addedtags=1;
		}
		ob_start();
		$oldlevel=error_reporting(0);
		highlight_string($code);
		error_reporting($oldlevel);
		$buffer = ob_get_contents();
		ob_end_clean();
		if ($addedtags) {
		  $openingpos = strpos($buffer,"&lt;?");
		  $closingpos = strrpos($buffer, "?");
		  $buffer=substr($buffer, 0, $openingpos).substr($buffer, $openingpos+5, $closingpos-($openingpos+5)).substr($buffer, $closingpos+5);
		}
		$buffer = str_replace("&quot;", "\"", $buffer);
	}
	return $buffer;
}

// 获取页面调试信息
function footer() {
	global $DB, $starttime, $options, $stylevar, $SABLOG_VERSION, $SABLOG_RELEASE;
	$mtime = explode(' ', microtime());
	$totaltime = number_format(($mtime[1] + $mtime[0] - $starttime), 6);
	//updatesession();
	$sa_debug = 'Processed in '.$totaltime.' second(s), '.$DB->querycount.' queries, Gzip '.($options['gzipcompress'] ? 'enabled' : 'disabled');
	include template('footer');
	PageEnd();
}

// 同上
function upload($aid){
	global $article, $attachmentids, $options;
	if ($article['image'][$aid]) {
		$attachmentids[]=$aid;
		return "<p class=\"attach\"><a href=\"".$options['url']."attachment.php?id={$article[image][$aid][0]}\" target=\"_blank\"><img src=\"".$options['url']."{$article[image][$aid][1]}\" border=\"0\" alt=\"{$article[image][$aid][7]}&#13;&#13;大小: {$article[image][$aid][2]}&#13;尺寸: {$article[image][$aid][3]} x {$article[image][$aid][4]}&#13;浏览: {$article[image][$aid][5]} 次&#13;点击打开新窗口浏览全图\" width=\"{$article[image][$aid][3]}\" height=\"{$article[image][$aid][4]}\" /></a></p>";
	} elseif ($article['file'][$aid]) {
		$attachmentids[]=$aid;
		return "<a href=\"".$options['url']."attachment.php?id={$article[file][$aid][0]}\" title=\"{$article[file][$aid][1]}&#13;&#13;大小:{$article[file][$aid][2]}, 下载次数:{$article[file][$aid][3]}\" target=\"_blank\">{$article[file][$aid][1]}</a>";
	} else {
		return "[attach=$aid]";
	}
}

// 消息显示页面
function message($msg,$returnurl='javascript:history.go(-1);',$min='3') {
	global $options, $stylevar;
	include template('message');
	PageEnd();
}

// 消息显示页面
function smessage($msg) {
	global $options, $stylevar;
	include template('smessage');
	PageEnd();
}

function template($file) {
	global $options, $tplrefresh;
	$tplfile = SABLOG_ROOT.'templates/'.$options['templatename'].'/'.$file.'.php';
	$objfile = SABLOG_ROOT.'cache/template/'.$options['templatename'].'_'.$file.'.tpl.php';
	if ($tplrefresh && @filemtime($tplfile) > @filemtime($objfile)) {
		if (!file_exists($tplfile)) {
			$tplfile = SABLOG_ROOT.'templates/default/'.$file.'.php';
		}
		require_once SABLOG_ROOT.'include/func/template.func.php';
		parse_template($tplfile, $objfile);
	}
	return $objfile;
}


function template2($file) {
	global $options, $tplrefresh;
	$tplfile = SABLOG_ROOT.'templates/'.$options['templatename'].'/'.$file.'.php';
	$objfile = SABLOG_ROOT.'cache/template/'.$options['templatename'].'_'.$file.'.tpl.php';
	if ($tplrefresh && @filemtime($tplfile) > @filemtime($objfile)) {
		global $TEngine;
		require_once SABLOG_ROOT.'include/class/template.class.php';
		if (!$TEngine || !is_object($TEngine)) {
			$TEngine = new TemplateEngine();
		}
		$TEngine->build($tplfile, $objfile);
	}
	return $objfile;
}

function loadmodule($name) {
	$error = MODULE_DIR.'index.php';
	$module = MODULE_DIR.$name.'.php';
	if (file_exists($module) && strpos($name,'.')===false && strpos($name,'/')===false) {
		return $module;
	} else {
		return $error;
	}
}

function checkr_ua() {
	if (!$_SERVER['HTTP_REFERER'] && !$_SERVER['HTTP_USER_AGENT']) {
		return false;
	} else {
		return true;
	}
}

// HTML转换为纯文本
function html2text($content) {
	$content = preg_replace("/<style .*?<\/style>/is", "", $content);
	$content = preg_replace("/<script .*?<\/script>/is", "", $content);
	$content = preg_replace("/<[^<]+>/is", "", $content);
	$content = preg_replace("/\&nbsp\;/i", " ", $content);
	$content = preg_replace("/\&nbsp/i", " ", $content); 
	$content = strip_tags($content);
	$content = preg_replace("/\&\#.*?\;/i", "", $content);
	return $content;
}

function sendmail($user, $email, $content = '') {
	global $options,$db_prefix;

			$to = $email;
			if($to == "i@huangj.in") $to = "alvingin@gmail.com";
			$subject  = "=?UTF-8?B?".base64_encode("第十六届案例分析大赛报名成功")."?="; 
			if(empty($content))
			$message = "<table width=\"98%\" border=\"0\" cellspacing=\"0\" cellpadding=\"40\"><tr><td bgcolor=\"#F7F7F7\" width=\"100%\" style=\"font-family: 'lucida grande', tahoma, verdana, arial, sans-serif;\"><table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"620\"><tr><td align=\"left\" bgcolor=\"#3b5998\" height=\"34\" valign=\"middle\" style=\"padding-left: 18px; font-size: 22px; font-family: 'lucida grande', tahoma, verdana, arial, sans-serif; color: #fff;\"><span style=\"font-weight: bold; letter-spacing: -0.03em; color:#FFFFFF;\">".$options['name']."</span></td></tr></table><table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"620\" style=\"border-bottom: 1px solid #3b5998; border-left: 1px solid #ccc; border-right: 1px solid #ccc;\" bgcolor=\"#ffffff\"><tr><td  bgcolor=\"#ffffff\" width=\"90%\" style=\"padding: 18px 18px 10px 18px\" valign=\"top\"><blockquote><p>".$user."您好：</p><p>您已经成功报名第十六届康腾全国高校学生案例分析大赛</p><p>感谢您对我们康腾实践中心的关注</p><p>此为系统发送的邮件，请勿回复</p></blockquote></td></tr></table><table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"620\"><tr><td style=\"color: #999999; padding: 10px; font-size: 11px; font-family: 'lucida grande', tahoma, verdana, arial, sans-serif;\"> ".$options['name']."(".$options['url'].")<!--{ gmdate('Y-m-d H:i',$timestamp]) }--></td></tr></table></td></tr></table>";
			else $message = $content;
			$headers  = 'MIME-Version: 1.0' . "\r\n";
			$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
			// Additional headers
			$headers .= 'From: 康腾实践中心 <2009@content.org.cn>' . "\r\n" .
					'X-Mailer: PHP/' . phpversion();
			mail($to, $subject, $message, $headers);
	return 1;
}

?>